package com.junit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcfly.utils.ESClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.BoostingQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;

public class BoolQueryDemo {
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String index = "fruit";
    private static final String type = "species";
    private static final RestHighLevelClient client = ESClient.getClient();

    @Test
    public void boostingQuery() throws IOException {
        /**
         * boosting 查询，根据两者匹配，进行分数的降分
         */
        SearchRequest request = new SearchRequest(index);
        request.types(type);

        SearchSourceBuilder builder = new SearchSourceBuilder();

        BoostingQueryBuilder boostring = QueryBuilders.boostingQuery(
                QueryBuilders.matchQuery("disc", "诱人甜瓜"),
                QueryBuilders.matchQuery("disc", "黄澄澄")
        ).negativeBoost(0.5f);

        builder.query(boostring);

        request.source(builder);

        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());

        }


    }

    @Test
    public void boolQuery() throws IOException {
        /**
         * bool查询为组合查询
         */
        SearchRequest request = new SearchRequest(index);
        request.types(type);

        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //# bool 组合查询
        //# 1，context包含 可口 甜瓜
        //# 2，name 为 番石榴 或者 奇异果
        //# 3， size不能为3
        boolQueryBuilder.should(QueryBuilders.termQuery("name", "番石榴"));
        boolQueryBuilder.should(QueryBuilders.termQuery("name", "奇异果"));

        boolQueryBuilder.mustNot(QueryBuilders.termQuery("size", 4));

        boolQueryBuilder.must(QueryBuilders.matchQuery("disc", "可口"));
        boolQueryBuilder.must(QueryBuilders.matchQuery("disc", "甜瓜"));

        builder.query(boolQueryBuilder);
        request.source(builder);

        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());

        }


    }

}
